<template>
  <div class="game-view">
    <!-- 导航栏 -->
    <nav class="navbar">
      <div class="container">
        <div class="nav-brand">
          <h1>🎮 {{ roomName || '游戏房间' }}</h1>
        </div>
        <div class="nav-info">
          <span class="room-code">房间码: {{ roomCode }}</span>
          <span :class="['connection-status', connectionStatus]">
            {{ connectionStatusText }}
          </span>
        </div>
      </div>
    </nav>

    <main class="main-content">
      <div class="game-container">
        <!-- 游戏状态栏 -->
        <div class="game-status-bar">
          <div class="status-left">
            <span :class="['status-badge', gameStatus]">
              {{ getStatusText(gameStatus) }}
            </span>
            <span v-if="gameStatus === 'playing'" class="timer">
              {{ formatTime(gameTime) }}
            </span>
          </div>
          <div class="status-right">
            <span class="player-count">{{ players.length }}/{{ maxPlayers }} 玩家</span>
          </div>
        </div>

        <!-- 游戏布局 -->
        <div class="game-layout">
          <!-- 左侧面板 - 玩家列表 -->
          <div class="left-panel">
            <div class="panel-header">
              <h3>玩家列表</h3>
              <button
                v-if="isHost && gameStatus === 'waiting'"
                @click="startGame"
                class="btn btn-primary"
                :disabled="!canStartGame"
              >
                开始游戏
              </button>
            </div>

            <div class="players-list">
              <div
                v-for="player in players"
                :key="player.id || player.Id"
                :class="[
                  'player-item',
                  {
                    'current-player': (player.id || player.Id) === currentPlayerId,
                    'is-host': player.isHost || player.IsHost,
                    'is-ready': player.isReady || player.IsReady,
                  },
                ]"
              >
                <div class="player-avatar" :style="{ backgroundColor: player.color }">
                  {{ (player.nickName || player.NickName || '?').charAt(0).toUpperCase() }}
                </div>
                <div class="player-info">
                  <div class="player-name">
                    {{ player.nickName || player.NickName || '未知玩家' }}
                  </div>
                  <div class="player-status">
                    <span v-if="player.isHost || player.IsHost" class="host-badge">房主</span>
                    <span
                      v-if="(player.isReady || player.IsReady) && gameStatus === 'waiting'"
                      class="ready-badge"
                      >已准备</span
                    >
                  </div>
                </div>
                <div
                  class="player-score"
                  v-if="gameStatus === 'playing' || gameStatus === 'finished'"
                >
                  {{ player.areaCount || player.AreaCount || 0 }}px²
                </div>
              </div>
            </div>

            <!-- 准备按钮 -->
            <div v-if="gameStatus === 'waiting'" class="ready-section">
              <button
                @click="toggleReady"
                :class="['btn', isReady ? 'btn-outline' : 'btn-success']"
              >
                {{ isReady ? '取消准备' : '准备就绪' }}
              </button>
            </div>
          </div>

          <!-- 中央游戏区域 -->
          <div class="center-panel">
            <div class="canvas-container">
              <GameCanvas
                ref="gameCanvasRef"
                :is-game-active="gameStatus === 'playing'"
                :game-time="gameTime"
                :players="players"
                :current-player-id="currentPlayerId"
                @paint-action="handlePaintAction"
              />
            </div>
          </div>

          <!-- 右侧面板 - 排行榜和工具 -->
          <div class="right-panel">
            <div class="panel-section">
              <h3>实时排名</h3>
              <div class="leaderboard">
                <div
                  v-for="(player, index) in sortedPlayers"
                  :key="player.id"
                  :class="['rank-item', { 'current-player': player.id === currentPlayerId }]"
                >
                  <span class="rank-number">{{ index + 1 }}</span>
                  <div class="rank-player">
                    <div class="rank-color" :style="{ backgroundColor: player.color }"></div>
                    <span class="rank-name">{{ player.nickName || '未知玩家' }}</span>
                  </div>
                  <span class="rank-score">{{ player.areaCount || 0 }}px²</span>
                </div>
              </div>
            </div>

            <div class="panel-section">
              <h3>工具栏</h3>
              <div class="tools">
                <button @click="clearCanvas" class="btn btn-outline btn-sm">🗑️ 清空画布</button>
                <button @click="leaveRoom" class="btn btn-danger btn-sm">🚪 离开房间</button>
              </div>
            </div>

            <div class="panel-section" v-if="gameStatus === 'finished'">
              <h3>游戏结果</h3>
              <div class="game-result">
                <div class="winner-info">
                  <h4>🎉 获胜者</h4>
                  <div class="winner-details">
                    <div class="winner-avatar" :style="{ backgroundColor: winner.color }">
                      {{ (winner.nickName || '?').charAt(0).toUpperCase() }}
                    </div>
                    <div class="winner-text">
                      <div class="winner-name">{{ winner.nickName || '未知玩家' }}</div>
                      <div class="winner-score">{{ winner.areaCount }}px²</div>
                    </div>
                  </div>
                </div>
                <div class="result-actions">
                  <button @click="playAgain" class="btn btn-primary">再来一局</button>
                  <button @click="backToLobby" class="btn btn-outline">返回大厅</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 加载中遮罩 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-content">
        <div class="spinner"></div>
        <p>{{ loadingMessage }}</p>
      </div>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error-message">
      <span class="error-icon">❌</span>
      <span>{{ error }}</span>
      <button @click="error = ''" class="close-btn">×</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { GameService } from '@/services/gameService'
import { socketService } from '@/services/socketService'
import GameCanvas from '@/components/GameCanvas.vue'

const route = useRoute()
const router = useRouter()

// 组件引用
const gameCanvasRef = ref(null)

// 状态
const loading = ref(true)
const loadingMessage = ref('正在连接游戏...')
const error = ref('')

// 游戏状态
const gameStatus = ref('waiting')
const gameTime = ref(0)
const totalGameTime = ref(180)
const roomId = ref('')
const roomCode = ref('')
const roomName = ref('')
const maxPlayers = ref(4)
const players = ref([])
const currentPlayerId = ref('')
const paintActions = ref([])

// 计算属性
const isHost = computed(() => {
  const player = players.value.find(
    (p) => p.Id === currentPlayerId.value || p.id === currentPlayerId.value,
  )
  return player?.IsHost || player?.isHost || false
})

const currentPlayer = computed(() => {
  return players.value.find((p) => p.Id === currentPlayerId.value || p.id === currentPlayerId.value)
})

const isReady = computed(() => {
  const player = players.value.find(
    (p) => p.Id === currentPlayerId.value || p.id === currentPlayerId.value,
  )
  return player?.IsReady || player?.isReady || false
})

const canStartGame = computed(() => {
  return (
    isHost.value &&
    gameStatus.value === 'waiting' &&
    players.value.length >= 2 &&
    players.value.every(
      (p) =>
        p.IsReady || p.isReady || p.Id === currentPlayerId.value || p.id === currentPlayerId.value,
    )
  )
})

const sortedPlayers = computed(() => {
  return [...players.value].sort(
    (a, b) => (b.AreaCount || b.areaCount || 0) - (a.AreaCount || a.areaCount || 0),
  )
})

const winner = computed(() => {
  if (gameStatus.value === 'finished' && sortedPlayers.value.length > 0) {
    return sortedPlayers.value[0]
  }
  return null
})

const connectionStatus = computed(() => {
  return socketService.getIsConnected() ? 'connected' : 'disconnected'
})

const connectionStatusText = computed(() => {
  return socketService.getIsConnected() ? '已连接' : '未连接'
})

// 工具函数
const getPlayerName = () => {
  try {
    // 首先尝试从localStorage获取全局昵称
    const globalPlayerName = localStorage.getItem('playerName')
    if (globalPlayerName) {
      return globalPlayerName
    }

    // 然后尝试从房间特定的localStorage获取昵称
    const storedPlayer = localStorage.getItem(`player_${route.params.roomId}`)
    if (storedPlayer) {
      const playerInfo = JSON.parse(storedPlayer)
      if (playerInfo && playerInfo.nickName) {
        return playerInfo.nickName
      }
    }

    // 如果没有保存的昵称，弹出输入框
    let name = prompt('请输入你的昵称（最多15个字符）：')

    // 如果用户取消输入或输入为空，使用默认昵称
    if (!name || name.trim() === '') {
      name = `玩家${Date.now().toString().slice(-4)}`
    }

    // 保存到全局localStorage
    localStorage.setItem('playerName', name.trim())

    return name.trim()
  } catch (error) {
    console.error('获取玩家昵称失败:', error)
    return `玩家${Date.now().toString().slice(-4)}`
  }
}

const getPlayerColor = (playerId) => {
  const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD']
  // 使用一个简单的哈希函数来确保颜色一致性
  let hash = 0
  const id = String(playerId || 'unknown')
  for (let i = 0; i < id.length; i++) {
    const char = id.charCodeAt(i)
    hash = (hash << 5) - hash + char
    hash = hash & hash // 转换为32位整数
  }
  return colors[Math.abs(hash) % colors.length]
}

const formatTime = (seconds) => {
  if (typeof seconds !== 'number' || seconds < 0) {
    return '0:00'
  }
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins}:${secs.toString().padStart(2, '0')}`
}

const getStatusText = (status) => {
  if (!status) {
    return '未知状态'
  }
  const statusMap = {
    waiting: '等待开始',
    playing: '游戏中',
    finished: '游戏结束',
  }
  return statusMap[status] || status
}

// 初始化游戏
const initializeGame = async () => {
  try {
    // 加强房间码参数验证，确保它是有效的非空字符串
    const code = route.params.roomId
    console.log('获取到的房间码参数:', code, '类型:', typeof code)
    if (!code || typeof code !== 'string' || code.trim() === '') {
      throw new Error('房间码无效')
    }

    loadingMessage.value = '正在连接游戏服务器...'

    // 连接Socket
    await socketService.connect()

    // 获取房间信息
    loadingMessage.value = '正在获取房间信息...'
    const { GameService } = await import('@/services/gameService')
    const roomInfo = await GameService.getGameByCode(code)

    console.log('房间信息:', roomInfo)
    roomId.value = roomInfo.id
    roomCode.value = roomInfo.code || roomInfo.Code || ''
    roomName.value = roomInfo.name || roomInfo.Name || '未命名房间'
    maxPlayers.value = roomInfo.maxPlayers || roomInfo.MaxPlayers || 4
    totalGameTime.value = roomInfo.gameDuration || roomInfo.GameDuration || 300
    gameTime.value = roomInfo.gameDuration || roomInfo.GameDuration || 300

    console.log('设置后的房间信息:', {
      roomId: roomId.value,
      roomCode: roomCode.value,
      roomName: roomName.value,
      maxPlayers: maxPlayers.value,
      totalGameTime: totalGameTime.value,
    })

    // 检查是否已经加入房间
    let storedPlayer = null
    let playerNickName = ''

    try {
      storedPlayer = localStorage.getItem(`player_${code}`)
    } catch (error) {
      console.error('读取本地存储失败:', error)
    }

    if (storedPlayer) {
      try {
        const playerInfo = JSON.parse(storedPlayer)
        if (playerInfo && playerInfo.nickName) {
          playerNickName = playerInfo.nickName

          // 从房间信息中查找当前玩家的完整信息
          const currentPlayerFromRoom = (roomInfo.Players || roomInfo.players || []).find(
            (p) => (p.NickName || p.nickName) === playerNickName,
          )

          if (currentPlayerFromRoom) {
            currentPlayerId.value = currentPlayerFromRoom.Id || currentPlayerFromRoom.id
            console.log('从房间信息中找到当前玩家:', currentPlayerId.value, currentPlayerFromRoom)
          } else if (playerInfo.id) {
            currentPlayerId.value = playerInfo.id
            console.log('使用localStorage中的玩家ID:', currentPlayerId.value)
          }

          // 确保房主信息正确
          if (currentPlayerFromRoom) {
            currentPlayerFromRoom.IsHost =
              currentPlayerFromRoom.IsHost ||
              currentPlayerFromRoom.isHost ||
              playerInfo.isHost ||
              false
            currentPlayerFromRoom.isHost = currentPlayerFromRoom.IsHost
          }

          // 如果已经加入，使用房间信息并确保所有玩家都有正确的信息
          players.value = (roomInfo.Players || roomInfo.players || []).map((p) => ({
            ...p,
            id: p.Id || p.id,
            nickName: p.NickName || p.nickName || p.name || p.Name || '未知玩家',
            isReady: p.isReady || p.IsReady || false,
            areaCount: p.areaCount || p.AreaCount || 0,
            color: getPlayerColor(p.Id || p.id || 'unknown'),
          }))

          console.log('已加入房间，当前玩家列表:', players.value)
        }
      } catch (error) {
        console.error('解析玩家信息失败:', error)
      }
    }

    if (!currentPlayerId.value || !playerNickName) {
      // 首次加入房间
      loadingMessage.value = '正在加入房间...'
      playerNickName = getPlayerName() // 只在首次加入时获取昵称
      const joinResult = await GameService.joinGame(code, playerNickName, null)

      // 查找当前玩家的ID
      const currentPlayerFromResult = (joinResult.Players || joinResult.players || []).find(
        (p) => (p.NickName || p.nickName) === playerNickName,
      )

      if (currentPlayerFromResult) {
        currentPlayerId.value = currentPlayerFromResult.Id || currentPlayerFromResult.id
        console.log('找到当前玩家ID:', currentPlayerId.value, '玩家信息:', currentPlayerFromResult)
      } else {
        console.warn('未找到当前玩家信息，使用时间戳作为ID')
        currentPlayerId.value = Date.now().toString()
      }

      players.value = (joinResult.Players || joinResult.players || []).map((p) => ({
        ...p,
        id: p.Id || p.id,
        nickName: p.NickName || p.nickName || p.name || p.Name || '未知玩家',
        isReady: p.isReady || p.IsReady || false,
        areaCount: p.areaCount || p.AreaCount || 0,
        color: getPlayerColor(p.Id || p.id || 'unknown'),
      }))

      // 保存玩家信息（只在首次加入时保存）
      try {
        const currentPlayerFromResult = (joinResult.Players || joinResult.players || []).find(
          (p) => (p.NickName || p.nickName) === playerNickName,
        )

        localStorage.setItem(
          `player_${code}`,
          JSON.stringify({
            id: currentPlayerId.value,
            nickName: playerNickName,
            isHost: currentPlayerFromResult?.IsHost || currentPlayerFromResult?.isHost || false,
          }),
        )
      } catch (error) {
        console.error('保存玩家信息失败:', error)
      }
    }

    // 设置Socket事件监听
    setupSocketListeners()

    // 加入Socket房间
    await socketService.joinRoom(
      roomCode.value,
      {
        id: currentPlayerId.value,
        nickName: playerNickName,
        isHost:
          players.value.find(
            (p) => p.Id === currentPlayerId.value || p.id === currentPlayerId.value,
          )?.IsHost ||
          players.value.find(
            (p) => p.Id === currentPlayerId.value || p.id === currentPlayerId.value,
          )?.isHost ||
          false,
        color: getPlayerColor(currentPlayerId.value || 'unknown'),
      },
      null,
    ) // 传递密码参数，这里使用null

    loading.value = false
  } catch (err) {
    error.value = `初始化游戏失败: ${err.message}`
    loading.value = false
    console.error('初始化游戏失败:', err)

    setTimeout(() => {
      if (router) {
        router.push('/lobby')
      }
    }, 3000)
  }
}

// 设置Socket事件监听
const setupSocketListeners = () => {
  socketService.on('playerJoined', (player) => {
    console.log('收到玩家加入事件:', player)
    if (player && (player.id || player.Id)) {
      const playerId = player.id || player.Id
      const existingPlayerIndex = players.value.findIndex(
        (p) => p.Id === playerId || p.id === playerId,
      )

      if (existingPlayerIndex >= 0) {
        // 更新现有玩家信息
        players.value[existingPlayerIndex] = {
          ...players.value[existingPlayerIndex],
          ...player,
          id: playerId,
          nickName: player.NickName || player.nickName || player.name || player.Name || '未知玩家',
          color: getPlayerColor(playerId || 'unknown'),
        }
      } else {
        // 添加新玩家
        players.value.push({
          ...player,
          id: playerId,
          nickName: player.NickName || player.nickName || player.name || player.Name || '未知玩家',
          isReady: false,
          areaCount: 0,
          color: getPlayerColor(playerId || 'unknown'),
        })
      }
      console.log('当前玩家列表:', players.value)
    }
  })

  socketService.on('playerLeft', (playerId) => {
    console.log('收到玩家离开事件:', playerId)
    if (playerId) {
      players.value = players.value.filter((p) => p.Id !== playerId && p.id !== playerId)
      console.log('玩家离开后，当前玩家列表:', players.value)
    }
  })

  socketService.on('playerReady', (playerId, isReady) => {
    console.log('收到玩家准备状态更新:', playerId, isReady)
    const player = players.value.find((p) => p.Id === playerId || p.id === playerId)
    if (player) {
      player.IsReady = isReady
      player.isReady = isReady
      console.log('更新玩家准备状态:', player.nickName, isReady)
    } else {
      console.warn('未找到玩家:', playerId)
    }
  })

  socketService.on('gameStarted', (gameData) => {
    gameStatus.value = 'playing'
    if (gameData && gameData.gameDuration) {
      gameTime.value = gameData.gameDuration
      totalGameTime.value = gameData.gameDuration
    }
  })

  socketService.on('gameEnded', (gameResult) => {
    gameStatus.value = 'finished'

    // 更新最终得分
    if (gameResult && gameResult.finalScores) {
      Object.entries(gameResult.finalScores).forEach(([playerId, score]) => {
        const player = players.value.find((p) => p.Id === playerId || p.id === playerId)
        if (player) {
          player.AreaCount = score
          player.areaCount = score
        }
      })
    }
  })

  socketService.on('paintAction', (action) => {
    if (gameCanvasRef.value && action && action.playerId !== currentPlayerId.value) {
      gameCanvasRef.value.handleRemotePaintAction(action)
    }
  })

  socketService.on('gameTimeUpdate', (timeRemaining) => {
    if (typeof timeRemaining === 'number' && timeRemaining >= 0) {
      gameTime.value = timeRemaining
    }
  })

  socketService.on('gameJoined', (game) => {
    console.log('收到游戏加入事件:', game)
    console.log('游戏对象类型:', typeof game)
    console.log('游戏对象键:', Object.keys(game || {}))

    if (game) {
      // 检查不同的可能属性名
      const playersData = game.players || game.Players || game.playerList || game.PlayerList || []
      console.log('找到的玩家数据:', playersData)

      if (Array.isArray(playersData) && playersData.length > 0) {
        players.value = playersData.map((p) => ({
          ...p,
          id: p.id || p.Id || p.playerId || p.PlayerId,
          nickName: p.NickName || p.nickName || p.name || p.Name || '未知玩家',
          isReady: p.isReady || p.IsReady || false,
          isHost: p.isHost || p.IsHost || false,
          areaCount: p.areaCount || p.AreaCount || 0,
          color: getPlayerColor(p.id || p.Id || p.playerId || p.PlayerId || 'unknown'),
        }))
        console.log('游戏加入后，当前玩家列表:', players.value)
      } else {
        console.warn('玩家数据为空或格式不正确:', playersData)
      }
    } else {
      console.warn('收到的游戏对象为空')
    }
  })

  socketService.on('error', (message) => {
    if (message) {
      error.value = message
    }
  })
}

// 事件处理
const toggleReady = async () => {
  try {
    if (roomCode.value) {
      const newReadyState = !isReady.value

      // 首先尝试通过昵称查找当前玩家
      let currentPlayer = null

      // 从localStorage获取玩家昵称
      const globalPlayerName = localStorage.getItem('playerName')
      const roomPlayerInfo = localStorage.getItem(`player_${roomCode.value}`)

      let playerNickName = null
      if (roomPlayerInfo) {
        try {
          const playerInfo = JSON.parse(roomPlayerInfo)
          playerNickName = playerInfo.nickName
        } catch (error) {
          console.error('解析房间玩家信息失败:', error)
        }
      }

      if (!playerNickName && globalPlayerName) {
        playerNickName = globalPlayerName
      }

      // 如果还是没有昵称，尝试从玩家列表中查找
      if (!playerNickName && players.value.length > 0) {
        // 尝试通过currentPlayerId查找
        if (currentPlayerId.value) {
          currentPlayer = players.value.find(
            (p) => p.Id === currentPlayerId.value || p.id === currentPlayerId.value,
          )
          if (currentPlayer) {
            playerNickName = currentPlayer.nickName || currentPlayer.NickName
          }
        }

        // 如果还是没找到，尝试查找第一个玩家（通常是房主）
        if (!playerNickName && players.value.length === 1) {
          currentPlayer = players.value[0]
          playerNickName = currentPlayer.nickName || currentPlayer.NickName
        }
      }

      if (!playerNickName) {
        error.value = '找不到当前玩家信息'
        console.error('找不到玩家昵称，当前状态:', {
          currentPlayerId: currentPlayerId.value,
          players: players.value,
          globalPlayerName,
          roomPlayerInfo,
        })
        return
      }

      console.log('准备设置玩家状态:', {
        roomCode: roomCode.value,
        playerNickName,
        newReadyState,
        currentPlayer,
      })

      // 使用玩家昵称调用setReady
      await socketService.setReady(roomCode.value, playerNickName, newReadyState)

      // 更新本地状态
      if (currentPlayer) {
        currentPlayer.IsReady = newReadyState
        currentPlayer.isReady = newReadyState
      }
    }
  } catch (err) {
    error.value = `设置准备状态失败: ${err.message}`
    console.error('设置准备状态失败:', err)
  }
}

const startGame = async () => {
  try {
    if (roomCode.value && currentPlayer.value) {
      console.log('开始游戏，房主信息:', {
        roomCode: roomCode.value,
        playerId: currentPlayer.value.Id || currentPlayer.value.id,
        playerName: currentPlayer.value.NickName || currentPlayer.value.nickName,
        isHost: currentPlayer.value.IsHost || currentPlayer.value.isHost,
      })

      await socketService.startGame(
        roomCode.value,
        currentPlayer.value.Id ||
          currentPlayer.value.id ||
          currentPlayer.value.NickName ||
          currentPlayer.value.nickName,
      )
    }
  } catch (err) {
    error.value = `开始游戏失败: ${err.message}`
    console.error('开始游戏失败:', err)
  }
}

const handlePaintAction = async (action) => {
  try {
    if (action && roomCode.value && currentPlayerId.value) {
      console.log('提交涂色动作:', {
        roomCode: roomCode.value,
        playerId: currentPlayerId.value,
        action: action,
      })

      // 确保传递正确的参数格式
      await socketService.submitPaintAction(
        roomCode.value,
        currentPlayerId.value,
        action.x,
        action.y,
        action.size || 5,
      )
    }
  } catch (err) {
    console.error('提交涂色动作失败:', err)
    error.value = `提交涂色动作失败: ${err.message}`
  }
}

const clearCanvas = () => {
  if (gameCanvasRef.value && typeof gameCanvasRef.value.clearCanvas === 'function') {
    gameCanvasRef.value.clearCanvas()
  }
}

const leaveRoom = async () => {
  try {
    if (roomCode.value && currentPlayerId.value) {
      await socketService.leaveRoom(roomCode.value, currentPlayerId.value)
    }
    router.push('/lobby')
  } catch (err) {
    error.value = `离开房间失败: ${err.message}`
  }
}

const playAgain = async () => {
  try {
    // 重置游戏状态
    gameStatus.value = 'waiting'
    gameTime.value = totalGameTime.value

    // 重置玩家状态
    if (players.value && players.value.length > 0) {
      players.value.forEach((player) => {
        if (player) {
          player.isReady = false
          player.areaCount = 0
        }
      })
    }

    // 清空画布
    if (gameCanvasRef.value) {
      gameCanvasRef.value.clearCanvas()
    }
  } catch (err) {
    error.value = `重新开始失败: ${err.message}`
  }
}

const backToLobby = () => {
  if (router) {
    router.push('/lobby')
  }
}

// 生命周期
onMounted(() => {
  initializeGame()
})

onUnmounted(() => {
  if (socketService && typeof socketService.disconnect === 'function') {
    socketService.disconnect()
  }
})
</script>

<style scoped>
.game-view {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
}

.navbar {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  padding: 1rem 0;
}

.navbar .container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 2rem;
}

.nav-brand h1 {
  color: white;
  margin: 0;
  font-size: 1.5rem;
}

.nav-info {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.room-code {
  color: white;
  font-family: monospace;
  font-weight: bold;
  background: rgba(255, 255, 255, 0.2);
  padding: 0.25rem 0.5rem;
  border-radius: 0.25rem;
}

.connection-status {
  color: white;
  font-size: 0.875rem;
}

.connection-status.connected {
  color: #4caf50;
}

.connection-status.disconnected {
  color: #ff6b6b;
}

.main-content {
  flex: 1;
  padding: 2rem;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

.game-container {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 1rem;
  padding: 1.5rem;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.game-status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  color: white;
}

.status-badge {
  padding: 0.5rem 1rem;
  border-radius: 1rem;
  font-weight: bold;
  font-size: 0.875rem;
}

.status-badge.waiting {
  background: #4caf50;
  color: white;
}

.status-badge.playing {
  background: #ff9800;
  color: white;
}

.status-badge.finished {
  background: #6c757d;
  color: white;
}

.timer {
  margin-left: 1rem;
  font-size: 1.25rem;
  font-weight: bold;
  color: #ffeaa7;
}

.player-count {
  color: white;
  font-size: 0.875rem;
}

.game-layout {
  display: grid;
  grid-template-columns: 300px 1fr 250px;
  gap: 1.5rem;
  min-height: 600px;
}

.left-panel,
.right-panel {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 0.75rem;
  padding: 1rem;
  color: white;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.panel-header h3 {
  margin: 0;
  font-size: 1.1rem;
}

.players-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  margin-bottom: 1rem;
}

.player-item {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.75rem;
  border-radius: 0.5rem;
  background: rgba(255, 255, 255, 0.1);
  transition: all 0.3s;
}

.player-item.current-player {
  border: 2px solid #ffeaa7;
}

.player-item.is-host {
  border: 2px solid gold;
}

.player-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  font-size: 1.1rem;
}

.player-info {
  flex: 1;
}

.player-name {
  font-weight: bold;
  margin-bottom: 0.25rem;
}

.player-status {
  font-size: 0.75rem;
}

.host-badge,
.ready-badge {
  padding: 0.125rem 0.375rem;
  border-radius: 0.25rem;
  font-size: 0.625rem;
  margin-left: 0.25rem;
}

.host-badge {
  background: gold;
  color: #333;
}

.ready-badge {
  background: #4caf50;
  color: white;
}

.player-score {
  font-weight: bold;
  font-family: monospace;
}

.ready-section {
  text-align: center;
}

.center-panel {
  display: flex;
  align-items: center;
  justify-content: center;
}

.canvas-container {
  background: white;
  border-radius: 0.75rem;
  padding: 1rem;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.panel-section {
  margin-bottom: 1.5rem;
}

.panel-section h3 {
  margin: 0 0 0.75rem 0;
  font-size: 1.1rem;
}

.leaderboard {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.rank-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 0.5rem;
  font-size: 0.875rem;
}

.rank-item.current-player {
  border: 1px solid #ffeaa7;
}

.rank-number {
  font-weight: bold;
  min-width: 20px;
}

.rank-player {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.rank-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.rank-name {
  flex: 1;
}

.rank-score {
  font-family: monospace;
  font-weight: bold;
}

.tools {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.game-result {
  text-align: center;
}

.winner-info h4 {
  margin: 0 0 0.75rem 0;
  color: #ffeaa7;
}

.winner-details {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  margin-bottom: 1rem;
}

.winner-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
}

.winner-name {
  font-weight: bold;
}

.winner-score {
  font-family: monospace;
}

.result-actions {
  display: flex;
  gap: 0.5rem;
}

.btn {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 0.5rem;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 0.875rem;
}

.btn-primary {
  background: #4caf50;
  color: white;
}

.btn-success {
  background: #4caf50;
  color: white;
}

.btn-outline {
  background: transparent;
  color: white;
  border: 1px solid white;
}

.btn-danger {
  background: #ff6b6b;
  color: white;
}

.btn-sm {
  padding: 0.5rem 1rem;
  font-size: 0.75rem;
}

.btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.loading-content {
  text-align: center;
  color: white;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(255, 255, 255, 0.3);
  border-top: 4px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 1rem;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.error-message {
  position: fixed;
  top: 20px;
  right: 20px;
  background: #ff6b6b;
  color: white;
  padding: 1rem 1.5rem;
  border-radius: 0.5rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  z-index: 1001;
  animation: slideIn 0.3s ease;
}

.error-icon {
  font-size: 1.2rem;
}

.close-btn {
  background: none;
  border: none;
  color: white;
  font-size: 1.5rem;
  cursor: pointer;
  margin-left: 0.5rem;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

@media (max-width: 1024px) {
  .game-layout {
    grid-template-columns: 1fr;
    gap: 1rem;
  }

  .left-panel,
  .right-panel {
    order: 2;
  }

  .center-panel {
    order: 1;
  }

  .main-content {
    padding: 1rem;
  }
}

@media (max-width: 768px) {
  .navbar .container {
    padding: 0 1rem;
  }

  .nav-brand h1 {
    font-size: 1.25rem;
  }

  .game-container {
    padding: 1rem;
  }

  .game-layout {
    grid-template-columns: 1fr;
  }
}
</style>
